package com.vision.shop.dao;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.vision.shop.model.Pager;
import com.vision.shop.model.ShopException;
import com.vision.shop.model.User;
import com.vision.shop.util.MyBatisUtil;

public class UserDao extends BaseDao<User> implements IUserDao {
	
	@Override
	public void add(User user) {
		User tu=this.loadByName(user.getUsername());
		if(tu!=null){
			throw new ShopException("要添加的用户已经存在");
		}else{
			super.add(user);
		}

	}

	@Override
	public void delete(int id) {
		//TODO 删除前需要先删除关联对象
		super.delete(User.class, id);
	}

	@Override
	public void update(User user) {
		SqlSession session=null;
		try {
			session=MyBatisUtil.createSession();
			session.update(User.class.getName()+".update", user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		}finally{
			MyBatisUtil.closeSession(session);
		}
	}


	@Override
	public User loadByName(String username) {
		return super.loadBySqlId(User.class.getName()+".load_by_username", username);
	}

	@Override
	public User load(int id) {
		SqlSession session=null;
		User u=null;
		try {
			session=MyBatisUtil.createSession();
			u=(User)session.selectOne(User.class.getName()+".load", id);
			
		}finally{
			MyBatisUtil.closeSession(session);
		}
		return u;
	}

	@Override
	public Pager<User> find(String name) {
		Map<String, Object> params=new HashMap<String,Object>();
		if(name!=null&&!name.equals(""))
		{
		params.put("name", "%"+name+"%");
		}
		return super.find(User.class, params);
	}

	@Override
	public User login(String username, String password) {
		User u=this.loadByName(username);
		if(u==null){
			throw new ShopException("用户名不存在");
		}
		if(!password.equals(u.getPassword())){
			throw new ShopException("用户密码不正确");
		}
		return u;
	}

}
